<script lang="ts" setup>
import { CloudUploadOutlined } from '@ant-design/icons-vue'
import type { Rule } from 'ant-design-vue/es/form'
import type { UploadFile } from 'ant-design-vue'
import { transferEmployeeData } from '../../functions/core'
import { AnalyzeExcel } from '@/module/attendanceManagement/utils/excel'
import { QAIndexDB } from '@/utils/indexDB'

withDefaults(
  defineProps<{
    title?: string
  }>(),
  {},
)

const emits = defineEmits(['confirm'])

// 表单
const formRef = ref()
const formData = reactive<{ employee?: UploadFile[] }>({
  employee: undefined,
})

// 表单验证规则
const rules: Record<string, Rule[]> = {
  employee: [
    { required: true, message: '请上传文件', trigger: 'change' },
  ],
}

// 确认上传
function onConfirm() {
  formRef.value.validate()
    .then(() => {
      onSubmit()
    })
    .catch(() => { })
}

// 提交数据
async function onSubmit() {
  const employeeFile = formData.employee?.[0]?.originFileObj
  if (!employeeFile) {
    return false
  }
  const excelData = await AnalyzeExcel(employeeFile)
  const employeeData = transferEmployeeData(excelData)
  if (employeeData) {
    QAIndexDB.setItem('EMPLOYEE', employeeData)
  }
  emits('confirm', employeeData)
}
</script>

<template>
  <Modal title="上传文件" @confirm="onConfirm">
    <a-form ref="formRef" :model="formData" :rules="rules">
      <a-form-item name="employee">
        <a-upload-dragger
          v-model:file-list="formData.employee" :before-upload="() => false" accept=".xlsx,.xls"
          :max-count="1"
        >
          <p class="ant-upload-drag-icon">
            <CloudUploadOutlined />
          </p>
          <p class="ant-upload-text">
            点击或拖拽上传考勤文件
          </p>
        </a-upload-dragger>
      </a-form-item>
    </a-form>
  </Modal>
</template>
